package org.ranshiyan.service;

import io.netty.util.internal.ObjectUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronScheduleBuilder;
import org.ranshiyan.dao.Iocdao;
import org.ranshiyan.po.DtoPo;
import org.ranshiyan.po.Hss1;
import org.ranshiyan.utils.ExceptionUtils;
import org.ranshiyan.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.swing.text.Segment;
import javax.swing.tree.TreeNode;
import java.io.*;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
public class LockService {

    @Value("${names}")
    private String names;

    @Autowired
    private StringRedisTemplate redisTemplate;

    Iocdao iocdao;

    public void setIocdao(Iocdao iocdao) {
        this.iocdao = iocdao;
    }

    public void seckillHandle(String key){
        /*System.out.println("666"+names);*/
        redisTemplate.opsForValue().set(key,"234");
        Boolean lockFlag = redisTemplate.opsForValue().setIfAbsent(key, "val", 10, TimeUnit.SECONDS);
        if (lockFlag) {
            String stock = (String)redisTemplate.opsForValue().get(key+":info");
            if(stock.isEmpty()){
                redisTemplate.opsForValue().set(key+":info","10");
            }else{
                redisTemplate.opsForValue().increment(key+":info", -1);
                System.out.println("生成订单");
                redisTemplate.delete(key);
                log.info("释放锁");
            }
        }else{
            log.info("该资源正在使用中");
        }
    }

    public void threadPoll(String key){
        Lock lock = new ReentrantLock();
        ExecutorService executor = Executors.newFixedThreadPool(5);
            executor.execute(new Runnable() { // 创建线程并添加到线程池中, 并启动运行线程
                @Override
                public void run() {
                    log.info("当前线程名称为"+Thread.currentThread().getName());
                    seckillHandle(key);
                }
            });
        executor.shutdown(); // 关闭线程池
        log.info("关闭线程"+Thread.currentThread().getName());
    }

    public void ioc1(){
        System.out.println("1111");
    }


    @Cacheable(value = "get",key="#key",unless = "#result.size()==0 || #result.size()==null")
    public void safedUnLock(String key, String val) {
        String luaScript = "local in = ARGV[1] local curr=redis.call('get', KEYS[1]) if in==curr then redis.call('del', KEYS[1]) end return 'OK'";
        RedisScript<String> redisScript = RedisScript.of(luaScript);
        redisTemplate.execute(redisScript, Collections.singletonList(key), Collections.singleton(val));
    }

    public void BaseCoder() throws Exception {
        String encode = FileUtils.encode("D:\\img111\\img\\123.jpg");
        System.out.println(encode);
        BASE64Decoder base64Decoder = new BASE64Decoder();
       /* encode = encode.substring(encode.indexOf(",") + 1).replaceAll(" ", "+");*/
        byte[] bytes = base64Decoder.decodeBuffer(encode);
        for (int i = 0;i<bytes.length;++i){
            if(bytes[i]<0){
                bytes[i]+=256;
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\img111\\123.jpg");
        fileOutputStream.write(bytes);
        fileOutputStream.flush();
        fileOutputStream.close();
    }

    @SneakyThrows
    public void time(){

        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("");
        Hss1 dtoPo = new Hss1();
        if(dtoPo!=null){
            throw new ExceptionUtils("123","12");
        }
        Segment segment = new Segment();
    }

}
